<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'

import { useUserStore } from '../../stores/index.ts'
import pageContainer from '../../components/pageContainer.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { updateUserService } from '../../api/user.ts'

const userStore = useUserStore()

onMounted(() => {
  console.log(userStore.user)
})

const ruleForm = ref<FormInstance>()
const checkNickname = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入用户昵称'))
  }
  if (value.length < 5 || value.length > 10) {
    return callback(new Error('用户昵称长度应在5到10个字符之间'))
  }
  callback()
}
const checkUsername = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入用户昵称'))
  }
  if (value.length < 5 || value.length > 10) {
    return callback(new Error('用户昵称长度应在5到10个字符之间'))
  }
  callback()
}
const checkEmail = (rule: any, value: anny, callback: any) => {
  if (!value) {
    return callback(new Error('请输入用户邮箱'))
  }
  // 邮箱正则验证
  const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (!emailPattern.test(value)) {
    return callback(new Error('请输入有效的邮箱地址'))
  }
  callback()
}

const formModel = ref({
  username: '',
  nickname: '',
  email: '',
})
formModel.value = userStore.user

const rules = reactive<FormRules<typeof formModel>>({
  username: [{ validator: checkUsername, trigger: 'blur' }],
  nickname: [{ validator: checkNickname, trigger: 'blur' }],
  email: [{ validator: checkEmail, trigger: 'blur' }],
})

// 修改事件
const onSubmit = async () => {
  await ElMessageBox.confirm('你确认此信息吗？', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
  const res = await updateUserService(formModel.value)
  console.log(res)
}
</script>

<template>
  <pageContainer title="个人信息">
    <el-form
      ref="ruleForm"
      :rules="rules"
      :model="formModel"
      status-icon
      class="demo-ruleForm"
      :size="formSize"
    >
      <el-form-item label="用户名称" prop="username">
        <el-input
          v-model="formModel.username"
          disabled
          style="width: 500px; height: 45px"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input
          v-model="formModel.nickname"
          placeholder="请输入用户昵称"
          style="width: 500px; height: 45px"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input
          v-model="formModel.email"
          placeholder="请输入用户邮箱"
          style="width: 500px; height: 45px"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交修改</el-button>
      </el-form-item>
    </el-form>
  </pageContainer>
</template>
